/**
 * http请求工具
 */
import axios from "axios"
import qs from 'qs'
import { merge } from 'lodash'
import { computed, ref } from "vue"
import {createDiscreteApi, darkTheme, lightTheme} from 'naive-ui'

// 配置
const baseURL = 'http://43.138.39.133:8809/'
const SUCCESS_CODE = 200
const ERROR_CODE = 500
const UNAUTHORISED_CODE = 401

// 创建axios实例
const request = axios.create({
    baseURL: baseURL,
    timeout: 10000,//请求超时时间10s
    headers: {
        common: {
            'X-Requested-With': 'XMLHttpRequest',
        }
    }
})

// naiveUI message组件
const themeRef = ref("light")
const configProviderPropsRef = computed(() => ({
    theme: themeRef.value === "light" ? lightTheme : darkTheme
}))
const { message } = createDiscreteApi(["message"], {configProviderProps: configProviderPropsRef})

// 请求拦截
// request.interceptors.request.use(function (config) {
//     return config
// }, function (error) {
//     return Promise.reject(error)
// })

// 响应拦截
request.interceptors.response.use(function (response) {
    const data = response.data
    switch(data.code) {
        case ERROR_CODE:// 业务错误
            message.error(data.msg)
            break
        case UNAUTHORISED_CODE:// 授权失效
            
            break
    }

    return data
}, function (error) {
    console.log(error)
    message.error(error.response.data || error.response.statusText || error.message)
    return Promise.reject(error)
})

// get函数
const get = (uri, config) => {
    return request.get(uri, config)
}

// post函数
const post = (uri, data, config = {}) => {
    return request.post(uri, qs.stringify(data), merge(config, {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        }
    }))
}

export {
    request,
    get,
    post,
}